#include "logon.h"
#include "ui_logon.h"
#include "widget.h"

#include <QHostAddress>

logon::logon(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::logon)
{
    ui->setupUi(this);
//    QPalette pal = this->palette();
//    pal.setBrush(QPalette::Background,QBrush(QPixmap("://p2.jpeg")));
//    setPalette(pal);
    setWindowTitle("用户注册");
    m_tcp = new QTcpSocket;
    m_tcp->connectToHost(QHostAddress("127.0.0.1"), 8888);
    ui->passwd->setEchoMode(QLineEdit::Password);
    ui->passwd_->setEchoMode(QLineEdit::Password);
    connect(ui->logon_, &QPushButton::clicked, this, &logon::logon_clicked);

}

logon::~logon()
{
    delete ui;
}

void logon::logon_clicked()
{
    //发送给服务器
    QString c_name = ui->usrname->text();
    QString c_passwd = ui->passwd->text();
    QString c_passwd2 = ui->passwd_->text();
    if (QString::compare("", c_name)==0 || QString::compare("", c_passwd)==0 || QString::compare("", c_passwd2)==0) {
        QMessageBox::information(this, "错误", "帐号或密码不能为空");
                return ;
    }
    if (QString::compare(c_passwd, c_passwd2) != 0) {
        QMessageBox::information(this, "错误", "两次输入的密码不相同");
                return ;
    }
    int type = 2;
    int name_len = c_name.size();
    int passwd_len = c_passwd.size();
    m_tcp->write((char*)&type, 4);
    m_tcp->write((char*)&name_len, 4);
    m_tcp->write(c_name.toUtf8());
    m_tcp->write((char*)&passwd_len, 4);
    m_tcp->write(c_passwd.toUtf8());
    connect(m_tcp, &QTcpSocket::readyRead, this, [=](){
        int type;
        m_tcp->read((char*)&type, 4);
        if (type == 2) {
            QByteArray data = m_tcp->readAll();
            QString back = data;
            QMessageBox::information(this, "注册成功", "帐号为" + back);
            Widget *w = new Widget;
            w->show();
            this->close();
        }
        qDebug() << "***";
    });
}
